import redis


class RedisOperator:
    def __init__(self, host='10.86.3.113', port=6379, db=0, password="123456"):
        """
        初始化 Redis 连接
        :param host: Redis 服务器地址
        :param port: Redis 服务器端口
        :param db: 要使用的 Redis 数据库编号
        :param password: Redis 服务器密码
        """
        try:
            self.redis_client = redis.Redis(
                host=host,
                port=port,
                db=db,
                password=password,
                decode_responses=True
            )
            # 测试连接
            self.redis_client.ping()
            print("成功连接到 Redis 服务器")
        except redis.exceptions.ConnectionError as e:
            print(f"连接 Redis 服务器时出错: {e}")
        except redis.exceptions.AuthenticationError as e:
            print(f"Redis 认证失败: {e}")

    def set_key(self, key, value, ex=None):
        """
        设置键值对
        :param key: 键
        :param value: 值
        :param ex: 过期时间（秒）
        :return: 设置成功返回 True，失败返回 False
        """
        try:
            return self.redis_client.set(key, value, ex=ex)
        except redis.exceptions.RedisError as e:
            print(f"设置键值对时出错: {e}")
            return False
        finally:
            self.redis_client.close()
    def get_key(self, key):
        """
        获取键对应的值
        :param key: 键
        :return: 键对应的值，如果键不存在返回 None
        """
        try:
            return self.redis_client.get(key)
        except redis.exceptions.RedisError as e:
            print(f"获取键值时出错: {e}")
            return None
        finally:
            self.redis_client.close()
    def delete_key(self, key):
        """
        删除键
        :param key: 键
        :return: 删除成功返回删除的键的数量，失败返回 0
        """
        try:
            return self.redis_client.delete(key)
        except redis.exceptions.RedisError as e:
            print(f"删除键时出错: {e}")
            return 0
        finally:
            self.redis_client.close()
    def set_expire(self, key, seconds):
        """
        为键设置过期时间
        :param key: 键
        :param seconds: 过期时间（秒）
        :return: 设置成功返回 True，失败返回 False
        """
        try:
            return self.redis_client.expire(key, seconds)
        except redis.exceptions.RedisError as e:
            print(f"设置过期时间时出错: {e}")
            return False
        finally:
            self.redis_client.close()

if __name__ == "__main__":
    # 使用示例
    redis_op = RedisOperator()
    # 设置键值对
    redis_op.set_key('/v1/archive/check_user_archive', 2)
    # redis_op.set_key('/v1/charge/lease/grant', '1')
    # redis_op.set_key('/v1/charge/stop', '1')
    # redis_op.set_key('/v1/charge/cancel', '1')
    # 获取键值
    # value = redis_op.get_key('/v1/charge/cid/')
    # print(f"键 test_key 的值: {value}")

    # 删除键
    # redis_op.set_key('/v1/aapmgr', 'GET')
    # redis_op.set_key('left_duration', '200')
    # deleted_count = redis_op.delete_key('/v1/aapmgr')


    # redis_op.set_key('/v1/charge/stop', '1')
    # deleted_count = redis_op.delete_key('/v1/charge/lease/grant')
    # deleted_count = redis_op.delete_key('/v1/charge/stop')
    deleted_count = redis_op.delete_key('/v1/archive/check_user_archive')
    # print(f"删除的键的数量: {deleted_count}")
